package com.cuiyun97.service.impl;

import com.cuiyun97.constant.DefaultConstant;
import com.cuiyun97.domain.po.SetOss;
import com.cuiyun97.service.SetOssService;
import com.cuiyun97.service.UploadService;
import com.cuiyun97.utils.AliOssUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * 文件上传
 *
 */
@Service
public class UploadServiceImpl implements UploadService {

    // oss 配置
    @Resource
    private SetOssService ossService;

    // ali oss 上传工具类
    @Resource
    private AliOssUtil aliOssUtil;

    @Override
    public String upload(MultipartFile file) {

        String url = "";

        // 配置
        SetOss set = ossService.getLastOne();

        // 根据不同保存类型操作
        Integer saveMode = set.getSaveMode();
        if (saveMode == DefaultConstant.SAVE_SERVER) {

            // 保存到服务器上, 目录不存在则创建
            // 目录 + bucket_name
            String saveServerPath = set.getSaveServerPath();
            File d = new File(saveServerPath + "/" + set.getBucketName());
            if (!d.exists()) {
                d.mkdirs();
            }

            // 创建文件名
            String filename = file.getOriginalFilename();
            int index = filename.indexOf(".");
            String extname = filename.substring(index);
            String newName = UUID.randomUUID() + extname;

            // 保存
            String saveName = saveServerPath + "/" + set.getBucketName() + "/" + newName;
            try {
                file.transferTo(new File(saveName));
                // 返回 / + bucket_name + 文件名
                url = "/" + set.getBucketName() + "/" + newName;
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else if (saveMode == DefaultConstant.SAVE_ALI_OSS) {

            // 保存到ali oss
            url = aliOssUtil.upload(file);
        }

        return url;
    }
}
